package com.qf.shop.order.controller;

import com.qf.shop.common.utils.R;
import com.qf.shop.common.vo.AddressVo;
import com.qf.shop.common.vo.OrderVo;
import com.qf.shop.common.vo.UserCarVo;
import com.qf.shop.order.entity.OrderEntity;
import com.qf.shop.order.feign.api.AddressService;
import com.qf.shop.common.vo.UserVo;
import com.qf.shop.order.feign.api.CarService;
import com.qf.shop.order.interceptor.LoginInterceptor;
import com.qf.shop.order.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.concurrent.ExecutionException;

@Controller
@RequestMapping("/order")
@Slf4j
public class OrderController {

    @Autowired
    private LoginInterceptor loginInterceptor;

    @Autowired
    private AddressService addressService;

    @Autowired
    private CarService carService;

    @Autowired
    private OrderService orderService;


    @PostMapping("/create")
    @ResponseBody
    public R create(@RequestBody OrderVo orderVo) throws ExecutionException, InterruptedException {
        log.debug("orderVO:{}", orderVo);
        String orderId = orderService.create(orderVo);
        return R.ok().put("orderId", orderId);
    }

    @GetMapping("/toOrderPay")
    public String toOrderPay(@RequestParam("key") HashSet<Object> key, ModelMap modelMap) {
        log.debug("kes:{}", key);

        // 1.获取登录用户的信息
        UserVo userVo = loginInterceptor.get();

        // 2.查询当前用户的收货地址
        List<AddressVo> addressList = addressService.getAddressListByUid(Integer.parseInt(userVo.getId()));

        // 3.查询用户勾选的商品信息
        StringBuffer keyStr = new StringBuffer();
        Object[] objects = key.toArray();
        for (int i = 0; i < objects.length; i++) {
            if (i != (objects.length - 1)) {
                keyStr.append(objects[i]).append(",");
            } else {
                keyStr.append(objects[i]);
            }
        }

        UserCarVo userCarVo = carService.getUserCar(keyStr.toString());

        // 4.把数组放到域中
        modelMap.put("addressList", addressList);
        modelMap.put("userCarVo", userCarVo);

        // 5.返回视图
        return "orderConfirm";
    }

    @GetMapping("/getOrderById/{orderId}")
    @ResponseBody
    public OrderEntity getOrderById(@PathVariable String orderId) {
        return orderService.getOrderById(orderId);
    }

    @GetMapping("/updateOrderStatus")
    @ResponseBody
    void updateOrderStatus(@RequestParam("orderId") String orderId, @RequestParam("status") Integer status) {
        orderService.updateOrderStatus(orderId,status);
    }
}
